<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="试卷名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入试卷名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
     <el-col :span="1.5">
       <el-button
         type="warning"
         icon="el-icon-download"
         size="mini"
         @click="handleExport"
       >导出</el-button>
     </el-col>
    </el-row>

    <el-table v-loading="loading" :data="paperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="试卷名称" align="center" prop="title" />
      <el-table-column label="题目数量" align="center" prop="questionNum" />
     <el-table-column label="答题人数" align="center" prop="answerNum" />
      <el-table-column label="正确率" align="center" prop="correctPercent" />
      <!--      列表switch 切换状态-->
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.shelfStatus"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试卷对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="试卷名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-form-item label="上架状态">
          <el-radio-group v-model="form.shelfStatus">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="已选试题" prop="startClassHour">
          <div class="optiondiv" v-if="isedit">
            <div
              v-for="(option,indexoption) in optionlist"
              :key="indexoption"
              style="border-bottom:1px solid #ccc;position: relative;padding-bottom:5px;"
            >
<!--              <div class="selQuestion">id：{{option.questionId}}</div>-->
              <div class="selQuestion">{{option.questionId}}：{{option.title}}</div>
              <i
                class="el-icon-delete"
                @click="deleteoption(indexoption)"
                style="position:absolute;top:10px;right:10px;"
              ></i>
            </div>
          </div>
          <div class="optiondiv" v-else>
            <div
              v-for="(option,indexoption) in optionlist"
              :key="indexoption"
              style="border-bottom:1px solid #ccc;position: relative;padding-bottom:5px;"
            >
<!--              <div class="selQuestion">id：{{option.questionId}}</div>-->
              <div class="selQuestion">{{option.questionId}}：{{option.title}}</div>
              <i
                class="el-icon-delete"
                @click="deleteoption(indexoption)"
                style="position:absolute;top:10px;right:10px;"
              ></i>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <el-dialog width="50%" title="选择试题" :visible.sync="innerVisible" append-to-body>
        <el-table
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChangein"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column :formatter="typeFormat" label="题型" prop="type"  width="50"></el-table-column>
          <el-table-column prop="title" label="题干" width="400"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip></el-table-column>
        </el-table>
        <pagination
          v-show="Qtotal>0"
          :total="Qtotal"
          :limit.sync="queryParamsQ.pageSize"
          :page.sync="queryParamsQ.pageNum"
          @pagination="getListQ"
        />
        <div style="margin-top: 20px">
          <el-button @click="selQuesSure">确定</el-button>
          <el-button @click="innercal">取消</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="innerVisible = true">选择试题</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listPaper, getPaper, delPaper, addPaper, updatePaper, exportPaper} from "@/api/system/paper";
  import { listQuestion } from "@/api/system/question";
  export default {
    name: "Paper",
    data() {
      return {
        // 展示选择试题
        isedit: false,
        optionlist: [],
        // 选择试题
        tableData: [],
        innerVisible: false,
        Qtotal: 0,

        statusOptions: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 试卷表格数据
        paperList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 数据字典
        typeOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: undefined,
          questionNum: undefined,
          answerNum: undefined,
          correctPercent: undefined,
          shelfStatus: undefined,
        },
        queryParamsQ: {
          pageNum: 1,
          pageSize: 10,
          answerId: undefined,
          analysis: undefined,
          questionType: undefined,
          shelfStatus: undefined,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
        }
      };
    },
    created() {
      this.getList();
      this.getListQ();
      this.getDicts("sys_shelf_status").then(response => {
        console.log(response.data)
        this.statusOptions = response.data;
      });
      this.getDicts("sys_question_type").then(response => {
        this.typeOptions = response.data;
      });
    },
    methods: {
      typeFormat(row, column) {
        return this.selectDictLabel(this.typeOptions, row.type);
      },
      // 选择试题
      deleteoption(e) {
        this.optionlist.splice(e, 1);
      },
      handleSelectionChangein(val) {
        this.multipleSelection = val;
      },
      selQuesSure() {
        this.optionlist = this.multipleSelection;
        console.log("选择试题列表", this.optionlist)
        this.innerVisible = false;
      },
      innercal() {
        this.innerVisible = false;
      },
      getListQ() {
        this.paramsData = this.queryParamsQ;
        this.loading = true;
        listQuestion(this.paramsData).then((response) => {
          this.tableData = response.rows;
          this.Qtotal = response.total;
          this.loading = false;
        });
      },
      // 试卷状态修改
      handleStatusChange(row) {
        console.log('aqie',row.shelfStatus)
        let text = row.shelfStatus == "0" ? "下架" : "上架";
        this.$confirm('确认要"' + text + '"试卷吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          let data = {
            "paperId":row.paperId,
            "shelfStatus":row.shelfStatus
          }
          return updatePaper(data);
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
      },
      /** 查询试卷列表 */
      getList() {
        this.loading = true;
        listPaper(this.queryParams).then(response => {
          console.log("paperList", response.rows)
          this.paperList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          paperId: undefined,
          title: undefined,
          questionNum: undefined,
          answerNum: undefined,
          correctPercent: undefined,
          shelfStatus: "0",
          delFlag: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          remark: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.paperId)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.isedit = false;
        this.optionlist = [];
        this.reset();
        this.open = true;
        this.title = "添加试卷";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.isedit = true;
        this.reset();
        const paperId = row.paperId || this.ids
        getPaper(paperId).then(response => {
          this.form = response.data;
          this.optionlist = response.data.paperQuestions2
          this.form.shelfStatus = this.form.shelfStatus + ""
          this.open = true;
          this.title = "修改试卷";
          console.log('edit',this.form, this.optionlist)
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.paperId != undefined) {
              let result = []
              this.optionlist.forEach(item => {
                let res = {
                  "questionId":item.questionId,
                  "paperId":this.form.paperId
                }
                result.push(res)
              })
              console.log('修改试卷', this.form,result)
              this.form.paperQuestions = result
              updatePaper(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else {
              let result = []
              this.optionlist.forEach(item => {
                let res = {
                  "questionId":item.questionId
                }
                result.push(res)
              })
              this.form.paperQuestions = result
              console.log('新增试卷', this.form, result)
              // return
              addPaper(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const paperIds = row.paperId || this.ids;
        this.$confirm('是否确认删除试卷编号为"' + paperIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPaper(paperIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有试卷数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportPaper(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
      }
    }
  };
</script>
